import { Controller, Inject, Post, Body } from '@midwayjs/core';
import { Context } from '@midwayjs/koa';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { UserEntity } from '../entity/user.entity';
import { Repository } from 'typeorm';
import { SQLGrammarError } from '../error/custom.error';
import { JwtPassportMiddleware } from '../middleware/jwt.middleware';
import { md5 } from '../utils';

// 该控制器主要用于处理状态相关业务
@Controller('/db')
export class DatabaseController {
  @Inject()
  ctx: Context;

  @InjectEntityModel(UserEntity)
  userModal: Repository<UserEntity>;

  // 执行SQL语句并返回数据
  @Post('/query', { middleware: [JwtPassportMiddleware] })
  async queryDatabase(@Body('sql') sql: string) {
    return await this.userModal.query(sql).then(
      res => res,
      () => {
        throw new SQLGrammarError();
      }
    );
  }

  // 用于初始化/重置数据库
  @Post('/init', { middleware: [JwtPassportMiddleware] })
  @Post('/reset', { middleware: [JwtPassportMiddleware] })
  async resetDB() {
    const allUser = await this.userModal.find();
    const initUser = new UserEntity('root', md5('root'));
    return await this.userModal.remove(allUser).then(
      async () => {
        await this.userModal.save(initUser);
        return { msg: 'Database reset successfully' };
      },
      err => ({ error: err })
    );
  }
}
